﻿using Common.Core.Exceptions;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Simple.Common.SignalR.Hubs
{
    public class StronglyTypedChatHub: Hub<IChatClient>
    {
        //private readonly IHttpContextAccessor _httpContextAccessor;

        ///// <summary>
        ///// 当前登录用户id
        ///// </summary>
        //public string UserId
        //{
        //    get
        //    {
        //        var userId = _httpContextAccessor.HttpContext.Request.Query["access_token"].FirstOrDefault();
        //        if (string.IsNullOrEmpty(userId))
        //        {
        //            throw new BusinessException("请使用get方式传递access_token");
        //        }
        //        return userId;
        //    }
        //}

        ///// <summary>
        ///// 医疗服务Hub 构造
        ///// </summary>
        //public StronglyTypedChatHub(IHttpContextAccessor httpContextAccessor)
        //{
        //    _httpContextAccessor = httpContextAccessor;
        //}
        ///// <summary>
        ///// 建立连接时触发
        ///// </summary>
        ///// <returns></returns>
        //public override async Task OnConnectedAsync()
        //{
        //    //1.保存链接客户id
        //    //2.发送返回消息
        //    await Clients.Caller.ReceiveMessage();
        //    await base.OnConnectedAsync();
        //}
        public async Task SendMessage(string user, string message)
        {
            await Clients.All.ReceiveMessage(user, message);
        }

        public Task SendMessageToCaller(string user, string message)
        {
            return Clients.Caller.ReceiveMessage(user, message);
        }

        public Task SendMessageToGroups(string user, string message)
        {
            return Clients.Group("SignalR Users").ReceiveMessage(user, message);
        }

        public override async Task OnConnectedAsync()
        {
            await Groups.AddToGroupAsync(Context.ConnectionId, "SignalR Users");
            await base.OnConnectedAsync();
        }

        public override async Task OnDisconnectedAsync(Exception exception)
        {
            await Groups.RemoveFromGroupAsync(Context.ConnectionId, "SignalR Users");
            await base.OnDisconnectedAsync(exception);
        }
    }
}
